package com.stardata.liangshisq.tcslmon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stardata.liangshisq.tcslmon.entity.SyncStatus;
import com.stardata.liangshisq.tcslmon.mapper.SyncStatusMapper;
import com.stardata.liangshisq.tcslmon.service.SyncStatusService;
import lombok.AllArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author Samson Shu
 * @email shush@stardata.top
 * @date 2020/7/31 14:54
 */
@Service
@AllArgsConstructor
public class SyncStatusServiceImpl extends ServiceImpl<SyncStatusMapper, SyncStatus>
    implements SyncStatusService{

  private final  SyncStatusMapper syncStatusMapper;

  @Override
  public Long getLastSyncId(int objectType) {
    QueryWrapper<SyncStatus> wrapper = new QueryWrapper<>();
    wrapper.eq("object_type", objectType);
    SyncStatus syncStatus = syncStatusMapper.selectOne(wrapper);
    return syncStatus == null? 0L: syncStatus.getLastId();
  }

  @Override
  public void updateLastSyncId(@NotNull Long objectId, int objectType) {
    SyncStatus syncStatus = new SyncStatus();
    syncStatus.setLastId(objectId);
    syncStatus.setObjectType(objectType);
    syncStatus.setUpdateTime(LocalDateTime.now());

    QueryWrapper<SyncStatus> wrapper = new QueryWrapper<>();
    wrapper.eq("object_type", objectType);
    SyncStatus oldSyncStatus = syncStatusMapper.selectOne(wrapper);
    if (oldSyncStatus == null) {
      syncStatusMapper.insert(syncStatus);
    } else {
      syncStatusMapper.update(syncStatus, wrapper);
    }
  }
}
